<template>
  <CustomScrollbar class="recommended-scroll">
    <div class="recommended">
      <h1 class="page-title">为你推荐</h1>
      
      <div v-if="recommendedSongs.length === 0" class="empty-state">
        <div class="empty-icon">🎵</div>
        <h3>暂无推荐音乐</h3>
        <p>我们正在为你准备个性化推荐</p>
        <button class="browse-btn" @click="$router.push('/library')">浏览音乐库</button>
      </div>
      
      <div v-else class="songs-list">
        <!-- 表格头部 -->
        <div class="table-header">
          <div class="header-cell header-index">#</div>
          <div class="header-cell header-title">标题</div>
          <div class="header-cell header-artist">艺人</div>
          <div class="header-cell header-album">专辑</div>
          <div class="header-cell header-duration">时长</div>
          <div class="header-cell header-actions"></div>
        </div>
        
        <!-- 歌曲列表 -->
        <div 
          class="song-row" 
          v-for="(song, index) in recommendedSongs" 
          :key="song.id"
          @mouseenter="hoveredRow = index"
          @mouseleave="hoveredRow = null"
          @dblclick="playMusic(song)"
        >
          <div class="song-cell song-index">
            <span v-if="hoveredRow !== index">{{ index + 1 }}</span>
            <button v-else class="play-btn" @click="playMusic(song)">
              <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
                <path d="M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14zm0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16z"/>
                <path d="M6.271 5.055a.5.5 0 0 1 .52.081L9.5 7.5a.5.5 0 0 1 0 .803L6.791 10.67a.5.5 0 0 1-.791-.407V5.73a.5.5 0 0 1 .271-.676z"/>
              </svg>
            </button>
          </div>
          <div class="song-cell song-title">
            <img v-if="song.cover" :src="song.cover" :alt="song.name" class="song-thumbnail">
            <MusicIcon v-else :size="40" class="song-thumbnail" />
            <div class="song-info">
              <div class="song-name">{{ song.name }}</div>
              <div class="song-artist-inline">{{ song.artist }}</div>
            </div>
          </div>
          <div class="song-cell song-artist">{{ song.artist }}</div>
          <div class="song-cell song-album">{{ song.album || '未知专辑' }}</div>
          <div class="song-cell song-duration">{{ formatDuration(song.duration) }}</div>
          <div class="song-cell song-actions">
            <button 
              class="action-btn favorite-btn" 
              @click="toggleFavorite(song)" 
              :class="{ 'favorited': isFavorite(song.id) }" 
              title="收藏/取消收藏"
            >
              <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
                <path d="M8 1.314C12.438-3.248 23.534 4.735 8 15-7.534 4.736 3.562-3.248 8 1.314z"/>
              </svg>
            </button>
          </div>
        </div>
      </div>
    </div>
  </CustomScrollbar>
</template>

<script>
import MusicIcon from '@/components/MusicIcon.vue'
import CustomScrollbar from '@/components/CustomScrollbar.vue'
import { musicAPI, playlistAPI } from '@/utils/api'

export default {
  components: {
    MusicIcon,
    CustomScrollbar
  },
  name: 'RecommendedView',
  data() {
    return {
      recommendedSongs: [],
      hoveredRow: null,
      loading: false
    }
  },
  async mounted() {
    // 加载收藏列表
    await this.$store.dispatch('player/loadFavorites')
    await this.loadRecommendedMusic()
  },
  computed: {
    favorites() {
      return this.$store.state.player.favorites || []
    }
  },
  methods: {
    async loadRecommendedMusic() {
      this.loading = true
      try {
        // 使用专门的推荐音乐API
        const response = await musicAPI.getRecommendedMusic(50)
        if (response.success && response.music) {
          this.recommendedSongs = response.music.map(music => ({
            id: music.musicId,
            name: music.name,
            artist: music.singer,
            album: music.singer, // 暂时使用歌手名作为专辑
            cover: this.buildCoverUrl(music.coverPath),
            duration: music.duration,
            filePath: this.buildAudioUrl(music.filePath)
          }))
          console.log('加载推荐音乐:', this.recommendedSongs.length, '首')
        } else {
          console.warn('获取推荐音乐失败')
          this.recommendedSongs = []
        }
      } catch (error) {
        console.error('加载推荐音乐失败:', error)
        this.recommendedSongs = []
        this.$toast?.error('加载推荐音乐失败，请稍后重试')
      } finally {
        this.loading = false
      }
    },

    buildCoverUrl(coverPath) {
      if (!coverPath) return null
      if (coverPath.startsWith('http')) return coverPath
      return `${process.env.VUE_APP_API_BASE_URL || 'http://localhost:8080'}${coverPath}`
    },

    buildAudioUrl(filePath) {
      if (!filePath) return null
      if (filePath.startsWith('http')) return filePath
      return `${process.env.VUE_APP_API_BASE_URL || 'http://localhost:8080'}${filePath}`
    },

    async playMusic(song) {
      try {
        console.log('播放音乐:', song.name)
        
        // 构建播放列表（推荐音乐列表）
        const playlist = this.songs.map(s => ({
          musicId: s.id,
          id: s.id,
          title: s.name,
          name: s.name,
          artist: s.artist,
          singer: s.artist,
          coverPath: s.cover,
          cover: s.cover,
          duration: s.duration,
          filePath: s.filePath,
          src: s.filePath
        }))
        
        // 设置播放列表
        this.$store.commit('player/SET_PLAYLIST', playlist)
        
        // 找到当前音乐在播放列表中的索引
        const currentIndex = playlist.findIndex(item => item.musicId === song.id)
        if (currentIndex !== -1) {
          this.$store.commit('player/SET_CURRENT_INDEX', currentIndex)
        }
        
        // 播放音乐
        this.$store?.dispatch('player/playMusic', {
          musicId: song.id,
          id: song.id,
          title: song.name,
          name: song.name,
          artist: song.artist,
          singer: song.artist,
          coverPath: song.cover,
          cover: song.cover,
          duration: song.duration,
          filePath: song.filePath,
          src: song.filePath
        })
        
        // 记录播放历史
        const userToken = localStorage.getItem('userToken')
        const userExpiry = localStorage.getItem('userTokenExpiry')
        
        if (userToken && userToken !== 'null' && userToken !== '' && userExpiry && Date.now() < parseInt(userExpiry)) {
          try {
            await playlistAPI.addPlayHistory(song.id)
            console.log('播放历史记录成功')
          } catch (error) {
            console.warn('记录播放历史失败:', error)
          }
        }
      } catch (error) {
        console.error('播放音乐失败:', error)
        this.$toast?.error('播放失败，请稍后重试')
      }
    },

    async toggleFavorite(song) {
      try {
        // 构建音乐数据对象
        const musicData = {
          musicId: song.id,
          id: song.id,
          title: song.name,
          name: song.name,
          artist: song.artist,
          singer: song.artist,
          cover: song.cover,
          duration: song.duration,
          filePath: song.filePath
        }
        
        // 使用Vuex store的toggleFavorite action
        await this.$store.dispatch('player/toggleFavorite', musicData)
        
        console.log('收藏操作成功:', song.name)
      } catch (error) {
        console.error('收藏操作失败:', error)
        this.$toast?.error('收藏操作失败，请稍后重试')
      }
    },

    isFavorite(songId) {
      return this.$store.getters['player/favorites'].includes(songId)
    },

    formatDuration(seconds) {
      // 处理各种输入情况
      if (seconds === null || seconds === undefined || seconds === 0) return '-'
      
      // 确保是数字类型
      const numSeconds = Number(seconds)
      if (isNaN(numSeconds) || numSeconds < 0) return '-'
      
      // 计算分钟和秒
      const minutes = Math.floor(numSeconds / 60)
      const remainingSeconds = Math.floor(numSeconds % 60)
      
      // 格式化输出
      if (minutes >= 60) {
        // 超过1小时的情况
        const hours = Math.floor(minutes / 60)
        const remainingMinutes = minutes % 60
        return `${hours}:${remainingMinutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
      } else {
        // 普通情况：分:秒
        return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
      }
    }
  }
}
</script>

<style scoped>
.recommended-scroll {
  height: 100%;
}

.recommended {
  padding-bottom: 24px;
}

.page-title {
  font-size: 2rem;
  margin-bottom: 32px;
  color: white;
  font-weight: 700;
}

.empty-state {
  text-align: center;
  padding: 64px 32px;
  color: #b3b3b3;
}

.empty-icon {
  font-size: 4rem;
  margin-bottom: 24px;
  opacity: 0.5;
}

.empty-state h3 {
  color: white;
  font-size: 2rem;
  margin-bottom: 16px;
}

.browse-btn {
  background: #1DB954;
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 24px;
  font-weight: bold;
  cursor: pointer;
  margin-top: 24px;
  transition: background 0.2s;
}

.browse-btn:hover {
  background: #1ed760;
}

.songs-list {
  background: transparent;
}

.table-header {
  display: grid;
  grid-template-columns: 50px 1fr 200px 200px 100px 60px;
  gap: 16px;
  padding: 8px 16px;
  border-bottom: 1px solid #282828;
  margin-bottom: 8px;
}

.header-cell {
  color: #b3b3b3;
  font-size: 12px;
  font-weight: 500;
  text-transform: uppercase;
  letter-spacing: 0.1em;
}

.song-row {
  display: grid;
  grid-template-columns: 50px 1fr 200px 200px 100px 60px;
  gap: 16px;
  padding: 8px 16px;
  border-radius: 4px;
  transition: background 0.2s;
  cursor: pointer;
}

.song-row:hover {
  background: rgba(255, 255, 255, 0.1);
}

.song-cell {
  display: flex;
  align-items: center;
  color: #b3b3b3;
  font-size: 14px;
}

.song-index {
  justify-content: center;
  color: #b3b3b3;
}

.play-btn {
  background: none;
  border: none;
  color: white;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  transition: all 0.2s;
}

.play-btn:hover {
  background: rgba(255, 255, 255, 0.1);
  transform: scale(1.05);
}

.song-title {
  gap: 12px;
}

.song-thumbnail {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  object-fit: cover;
  flex-shrink: 0;
}

.song-info {
  min-width: 0;
  flex: 1;
}

.song-name {
  color: white;
  font-weight: 400;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.song-artist-inline {
  color: #b3b3b3;
  font-size: 13px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.song-artist,
.song-album {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.song-duration {
  justify-content: flex-end;
  font-variant-numeric: tabular-nums;
}

.song-actions {
  justify-content: center;
  opacity: 0;
  transition: opacity 0.2s;
}

.song-row:hover .song-actions {
  opacity: 1;
}

.action-btn {
  background: none;
  border: none;
  color: #b3b3b3;
  cursor: pointer;
  padding: 4px;
  border-radius: 50%;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
}

.action-btn:hover {
  color: white;
  background: rgba(255, 255, 255, 0.1);
  transform: scale(1.05);
}

.favorite-btn.favorited {
  color: #1DB954;
}

.favorite-btn.favorited:hover {
  color: #1ed760;
}

@media (max-width: 768px) {
  .table-header,
  .song-row {
    grid-template-columns: 40px 1fr 80px 50px;
    gap: 8px;
  }
  
  .song-artist,
  .song-album {
    display: none;
  }
  
  .header-artist,
  .header-album {
    display: none;
  }
}
</style> 